<template>
	<div :id="id" class="app-mob-html-container view-container">
		<iframe ref="iframe" :src="url"></iframe>
	</div>
</template>
<script lang="ts" setup>
import { createUUID } from '@/core';
import { Ref } from 'vue';
import { htmlContainerProps } from './html-container';
import { useRouter } from 'vue-router';
import { useAppStoreWithOut } from '@/store';
const props = defineProps(htmlContainerProps);
const curRoute = useRouter().currentRoute.value;
const { setPage } = useAppStoreWithOut();

let loadingBindElement: any = null;

const id = createUUID();

const iframe: Ref<any> = ref(null);

const url: Ref<any> = computed(() => {
	let url = props.htmlUrl;
	if (props.viewParams && props.viewParams.htmlPageUrl) {
		url = props.viewParams.htmlPageUrl;
	} else if ((curRoute.params as any).apphtmlview) {
		url = (curRoute.params as any).apphtmlview;
		setPage({
			fullPath: curRoute.fullPath,
			caption: curRoute.query.caption as string,
		});
	}
	return url;
});

const beginLoading = () => {
	const element = document.getElementById(id);
	if (element) {
		element.style.pointerEvents = 'none';
		const loadingMask = document.createElement('div');
		loadingMask.classList.add('loading-mask', `loading-mask-view`);
		loadingMask.id = `loading-mask-${id}`;
		const loadingMaskSpin = `
        <div class="loading-mask__spin">
            <span class="loading-mask__spin-container">
            <span class="loading-mask__spin-item"></span>
            <span class="loading-mask__spin-item"></span>
            <span class="loading-mask__spin-item"></span>
            <span class="loading-mask__spin-item"></span>
            </span>
        <div class="loading-mask__blur"></div>`;
		loadingMask.innerHTML = loadingMaskSpin;
		element.appendChild(loadingMask);
		loadingBindElement = element;
	}
};

const endLoading = () => {
	if (loadingBindElement) {
		loadingBindElement.style.pointerEvents = 'auto';
		const lastChild = loadingBindElement.lastChild as HTMLElement;
		if (lastChild && lastChild.classList.contains('loading-mask')) {
			lastChild.remove();
		}
	}
};

const iframeLoad = () => {
	if (url.value) {
		beginLoading();
		const IFrame = iframe.value;
		if (IFrame) {
			if (IFrame.attachEvent) {
				IFrame.attachEvent('onload', () => {
					endLoading();
				});
			} else {
				IFrame.onload = () => {
					endLoading();
				};
			}
		} else {
			endLoading();
		}
	}
};

onMounted(() => {
	iframeLoad();
});
</script>
